from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import argparse
import time

def fill_web_form(excel_file, form_url, field_mapping, delay=2):
    """
    自动填充网页表单
    :param excel_file: 包含数据的Excel文件
    :param form_url: 表单网页URL
    :param field_mapping: 字段映射（Excel列名:表单元素ID）
    :param delay: 操作延迟时间(秒)
    """
    try:
        # 读取Excel数据
        df = pd.read_excel(excel_file)
        print(f"读取到 {len(df)} 条数据，开始自动填充...")
        
        # 初始化浏览器
        driver = webdriver.Chrome()  # 需要安装ChromeDriver并配置到PATH
        driver.maximize_window()
        
        # 逐个填充表单
        for index, row in df.iterrows():
            try:
                # 打开表单页面
                driver.get(form_url)
                time.sleep(delay)
                
                # 填充字段
                for excel_col, form_id in field_mapping.items():
                    if pd.notna(row[excel_col]):
                        # 等待元素加载
                        element = WebDriverWait(driver, 10).until(
                            EC.presence_of_element_located((By.ID, form_id))
                        )
                        # 清除并输入值
                        element.clear()
                        element.send_keys(str(row[excel_col]))
                        time.sleep(0.5)
                
                # 等待用户确认提交（实际应用中可自动提交）
                input(f"\n已填充第 {index+1}/{len(df)} 条数据，请检查。按Enter继续...")
                
            except Exception as e:
                print(f"处理第 {index+1} 条数据时出错: {str(e)}")
                retry = input("是否重试？(y/n): ")
                if retry.lower() != 'y':
                    continue
        
        print("\n所有数据处理完成")
        driver.quit()
        
    except Exception as e:
        print(f"自动填充失败: {str(e)}")

if __name__ == "__main__":
    # 安装依赖提示
    try:
        import pandas
        import openpyxl
        from selenium import webdriver
    except ImportError:
        print("请先安装依赖: pip install pandas openpyxl selenium")
        exit(1)
    
    parser = argparse.ArgumentParser(description='网页表单自动填充工具')
    parser.add_argument('excel', help='包含数据的Excel文件')
    parser.add_argument('url', help='表单网页URL')
    parser.add_argument('--mapping', required=True, 
                      help='字段映射，格式:Excel列1:表单ID1,Excel列2:表单ID2')
    
    args = parser.parse_args()
    
    # 解析字段映射
    field_mapping = {}
    for pair in args.mapping.split(','):
        if ':' in pair:
            excel_col, form_id = pair.split(':', 1)
            field_mapping[excel_col.strip()] = form_id.strip()
    
    fill_web_form(
        excel_file=args.excel,
        form_url=args.url,
        field_mapping=field_mapping
    )
